package com.yike.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yike.common.exception.BusinessException;
import com.yike.common.pagination.PageInfo;
import com.yike.common.pagination.Paging;
import com.yike.common.tool.StringUtil;
import com.yike.product.dto.BarcodeDto;
import com.yike.product.entity.Barcode;
import com.yike.product.listener.GoodsExcelListener;
import com.yike.product.mapper.*;
import com.yike.product.param.PlatformGoodsPageParam;
import com.yike.product.param.PlatformGoodsParam;
import com.yike.product.param.PlatformShopGoodsPageParam;
import com.yike.product.service.PlatformGoodsService;
import com.yike.product.vo.PlatformGoodsVo;
import com.yike.product.vo.PlatformShopGoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/**
 * 商品库管理 服务实现类
 *
 * @author Sakura
 * @since 2024-10-18
 */
@Slf4j
@Service
public class PlatformGoodsServiceImpl implements PlatformGoodsService {

    @Autowired
    private BarcodeMapper barcodeMapper;
    @Autowired
    private GoodsBrandMapper goodsBrandMapper;
    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;
    @Autowired
    private GoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    private GoodsSupplierMapper goodsSupplierMapper;
    @Autowired
    private GoodsUnitMapper goodsUnitMapper;


    @Override
    public boolean batchSave(List<PlatformGoodsParam> platformGoodsParams) throws Exception {
        if (platformGoodsParams == null || platformGoodsParams.size() < 1) {
            throw new BusinessException("商品信息不能为空");
        }
        for (PlatformGoodsParam goodsParam : platformGoodsParams) {
            // 如果条形码为空随机生成一个
            if (StringUtil.isBlank(goodsParam.getCode())) {
                goodsParam.setCode(generateCode());
            }
            // 条码不能重复
            Barcode barcode = barcodeMapper.selectOne(Wrappers.lambdaQuery(Barcode.class)
                    .eq(Barcode::getCode, goodsParam.getCode()));
            if (barcode != null) {
                throw new BusinessException("商品条码已存在：" + goodsParam.getCode());
            }
            barcode = new Barcode();
            BeanUtils.copyProperties(goodsParam, barcode);
            barcodeMapper.insert(barcode);
        }
        return true;
    }

    @Override
    public boolean batchUpdate(List<PlatformGoodsParam> platformGoodsParams) throws Exception {
        if (platformGoodsParams == null || platformGoodsParams.size() < 1) {
            throw new BusinessException("商品信息不能为空");
        }
        for (PlatformGoodsParam goodsParam : platformGoodsParams) {
            // 修改的时候要防止条码和原有的重复
            Barcode checkBarcode = barcodeMapper.selectOne(Wrappers.lambdaQuery(Barcode.class)
                    .eq(Barcode::getCode, goodsParam.getCode())
                    .ne(Barcode::getId, goodsParam.getId()));
            if (checkBarcode != null) {
                throw new BusinessException("商品条码已存在：" + goodsParam.getCode());
            }
            // 获取原商品信息
            Barcode barcode = barcodeMapper.selectById(goodsParam.getId());
            if (barcode == null) {
                throw new BusinessException("商品信息异常");
            }
            BeanUtils.copyProperties(goodsParam, barcode);
            barcodeMapper.updateById(barcode);
        }
        return true;
    }

    @Override
    public boolean batchDel(List<Long> ids) throws Exception {
        if (ids == null || ids.size() < 1) {
            throw new BusinessException("请求参数异常");
        }
        barcodeMapper.deleteBatchIds(ids);
        return true;
    }

    @Override
    public PlatformGoodsVo getGoods(Long id) throws Exception {
        return barcodeMapper.getPlatformGoodsVo(id);
    }

    @Override
    public Paging<PlatformGoodsVo> getGoodsList(PlatformGoodsPageParam platformGoodsPageParam) throws Exception {
        Page<PlatformGoodsVo> page = new PageInfo<>(platformGoodsPageParam);
        IPage<PlatformGoodsVo> iPage = barcodeMapper.getGoodsList(page, platformGoodsPageParam);
        return new Paging<PlatformGoodsVo>(iPage);
    }

    @Override
    @Transactional
    public boolean importGoods(MultipartFile file) throws Exception {
        try {
            EasyExcel.read(file.getInputStream(), BarcodeDto.class, new GoodsExcelListener(barcodeMapper, goodsBrandMapper,
                            goodsCategoryMapper, goodsSpecificationMapper, goodsSupplierMapper, goodsUnitMapper))
                    .sheet(0)
                    .headRowNumber(1)
                    .doRead();
        } catch (IOException e) {
            log.error("导入商品数据异常：{}", e.getMessage());
            e.printStackTrace();
            throw new BusinessException("导入商品数据异常");
        }
        return true;
    }

    @Override
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "商品信息模板.xlsx";

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 处理文件名以防止中文乱码
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);

        // 将Excel文件写入到响应的输出流中
        EasyExcel.write(response.getOutputStream(), BarcodeDto.class)
                .sheet("商品信息")
                .doWrite(Collections.emptyList()); // 传入空列表，只生成表头
    }

    @Override
    public Paging<PlatformShopGoodsVo> getShopGoodsList(PlatformShopGoodsPageParam platformGoodsPageParam) throws Exception {
        Page<PlatformShopGoodsVo> page = new PageInfo<>(platformGoodsPageParam);
        IPage<PlatformShopGoodsVo> iPage = barcodeMapper.getShopGoodsList(page, platformGoodsPageParam);
        return new Paging<PlatformShopGoodsVo>(iPage);
    }

    public static String generateCode() {
        // 获取当前日期，并格式化为 yyMMdd（去掉年前两位）
        String datePrefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyMMdd"));

        // 生成 7 位随机数字
        Random random = new Random();
        int randomNum = 1000000 + random.nextInt(9000000); // 确保是 7 位数

        // 拼接成最终编码
        return datePrefix + randomNum;
    }

}
